package com.sites.cms.permission;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpSession;

import com.jfinal.aop.Inject;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.Ret;
import com.sites.common.SiteInfo;
import com.sites.common.model.Account;
import com.sites.common.model.Permission;

/**
 * 全局权限拦截器
 * <br/>不具备权限的不能访问，避免直接在地址栏输入请求地址
 * 
 * @author zyg
 * 2020年1月31日 下午8:28:42
 */
public class PermissionInterceptor implements Interceptor {

	@Inject
	private PermissionService permSrv;
	
	public void intercept(Invocation inv) {
		//有多个条件需要判断，需要预设一个标志
		boolean flag = false;
		
		Controller c = inv.getController();
		HttpSession session = c.getSession();
		Account account = (Account) session.getAttribute(SiteInfo.account);
		String actionKey = inv.getActionKey();
		
		//超级管理员不需要拦截，直接放行
		if(SiteInfo.adminName.equals(account.getUserName())){
			flag = true;
		}
		
		//判断权限是否有效
		if(!flag){
			Permission permission = permSrv.getByActionKey(actionKey, SiteInfo.siteId);
			//已删除的权限直接放行
			if(permission!=null && SiteInfo.statusDel.equals(permission.getStatus())){
				flag = true;
			}
		}
		
		
		//判断用户权限中是否有要访问的请求
		if(!flag){
			List<Permission> permList = permSrv.getAccountPerm(account.getId());
			List<String> actionKeyList = new ArrayList<String>();
			for(Permission p : permList){
				actionKeyList.add(p.getActionKey());
			}
			if(actionKeyList.contains(actionKey)){
				flag = true;
			}
		}
		 
		
		if(flag){
			inv.invoke();
		} else {
			String methodName = inv.getMethodName();
			//根据不同的请求方法进行提示处理，依托于sitesCMS设计规范
			if(methodName.startsWith("enter")){
				c.render("/cms/common/noPermission.html");
			} else {
				Ret ret = Ret.fail(SiteInfo.msgKey, "暂无处理权限！");
				c.renderJson(ret);
			}
		}
	}

}
